<template>
  <div class="component-upload-dicom">
    <el-upload
      multiple
      :auto-upload="false"
      list-type="text"
      :on-change="handleFileChange"
      :before-upload="handleBeforeUpload"
      :limit="limit"
      :on-exceed="handleExceed"
      ref="dicomUpload"
      :before-remove="handleDelete"
      :show-file-list="true"
      :file-list="fileList"
      :on-preview="handleFilePreview"
      :class="{ hide: fileList.length >= limit }"
      :disabled="disabled"
    >
      <el-button type="primary" size="default">
        <el-icon class="el-icon--upload"><Plus /></el-icon>
        选择文件
      </el-button>
      <template #tip>
        <div class="el-upload__tip" v-if="showTip && !disabled">
          请上传
          <template v-if="fileSize">
            大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b>
          </template>
          的文件
        </div>
      </template>
    </el-upload>
    
    <!-- 文件统计 -->
    <div v-if="fileList.length > 0" class="file-stats">
      <el-alert
        :title="`已选择 ${fileList.length} 个文件，总大小 ${formatFileSize(totalFileSize)}`"
        type="info"
        :closable="false"
        show-icon
      />
    </div>

    <!-- 上传成功统计信息 -->
    <el-card v-if="uploadResult" class="upload-result-card" shadow="never">
      <template #header>
        <div class="card-header">
          <span style="font-weight: bold; color: #67c23a;">上传成功</span>
        </div>
      </template>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="任务ID">{{ uploadResult.taskId }}</el-descriptions-item>
        <el-descriptions-item label="检查数量">{{ uploadResult.studyCount }}</el-descriptions-item>
        <el-descriptions-item label="序列数量">{{ uploadResult.seriseCount }}</el-descriptions-item>
        <el-descriptions-item label="处理文件数">{{ uploadResult.processedFiles }}</el-descriptions-item>
      </el-descriptions>
      <div style="margin-top: 15px; text-align: center;">
        <el-button type="success" @click="viewTaskDetails">查看任务详情</el-button>
        <el-button @click="uploadResult = null">关闭</el-button>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { getToken } from "@/utils/auth"
import { isExternal } from "@/utils/validate"
import { ref, computed, watch, getCurrentInstance } from 'vue'
import { Plus } from '@element-plus/icons-vue'

const props = defineProps({
  modelValue: {
    type: [String, Object, Array],
    default: ''
  },
  action: {
    type: String,
    default: "/pacs/dicom/upload/folder"
  },
  data: {
    type: Object,
    default: () => ({})
  },
  limit: {
    type: Number,
    default: 100
  },
  fileSize: {
    type: Number,
    default: 50
  },
  isShowTip: {
    type: Boolean,
    default: true
  },
  disabled: {
    type: Boolean,
    default: false
  }
})

const { proxy } = getCurrentInstance()
const emit = defineEmits()
const uploading = ref(false)
const baseUrl = import.meta.env.VITE_APP_BASE_API
const uploadDicomUrl = ref(import.meta.env.VITE_APP_BASE_API + props.action)
const fileList = ref([])
const uploadResult = ref(null)
const rawFiles = ref([]) // 存储原始文件对象

// 计算总文件大小
const totalFileSize = computed(() => {
  return fileList.value.reduce((total, file) => total + (file.size || 0), 0)
})

const showTip = computed(
  () => props.isShowTip && props.fileSize
)

// 文件选择变化
function handleFileChange(file, fileList) {
  console.log('文件变化:', file, fileList)
  
  // 只有当文件状态是 ready 时才添加到 rawFiles
  if (file.status === 'ready' && file.raw) {
    // 检查是否已存在同名文件
    const existingIndex = rawFiles.value.findIndex(f => f.name === file.name)
    if (existingIndex === -1) {
      rawFiles.value.push(file.raw)
    }
  }
  
  // 更新 fileList
  updateFileList(fileList)
}

// 更新文件列表
function updateFileList(newFileList) {
  fileList.value = newFileList.map(file => {
    return {
      name: file.name,
      size: file.size,
      status: file.status,
      raw: file.raw
    }
  })
}

// 上传前验证
function handleBeforeUpload(file) {
  // 检查文件名是否包含逗号
  if (file.name.includes(',')) {
    proxy.$modal.msgError('文件名不正确，不能包含英文逗号!')
    return false
  }
  
  // 检查文件大小
  if (props.fileSize) {
    const isLt = file.size / 1024 / 1024 < props.fileSize
    if (!isLt) {
      proxy.$modal.msgError(`上传文件大小不能超过 ${props.fileSize} MB!`)
      return false
    }
  }
  
  return true
}

// 文件个数超出
function handleExceed() {
  proxy.$modal.msgError(`上传文件数量不能超过 ${props.limit} 个!`)
}

// 删除文件
function handleDelete(file) {
  const findex = fileList.value.findIndex(f => f.name === file.name)
  if (findex > -1) {
    fileList.value.splice(findex, 1)
    
    // 同时从 rawFiles 中删除
    const rawIndex = rawFiles.value.findIndex(f => f.name === file.name)
    if (rawIndex > -1) {
      rawFiles.value.splice(rawIndex, 1)
    }
    
    emit("update:modelValue", listToString(fileList.value))
    return false
  }
}

// 文件预览（查看文件信息）
function handleFilePreview(file) {
  console.log('预览文件:', file)
  proxy.$modal.msgInfo(`文件名: ${file.name}, 大小: ${formatFileSize(file.size)}`)
}

// 查看任务详情
function viewTaskDetails() {
  if (uploadResult.value && uploadResult.value.taskId) {
    proxy.$modal.msgInfo(`查看任务详情: ${uploadResult.value.taskId}`)
  }
}

// 对象转成指定字符串分隔
function listToString(list, separator) {
  let strs = ""
  separator = separator || ","
  for (let i in list) {
    if (undefined !== list[i].url && list[i].url.indexOf("blob:") !== 0) {
      strs += list[i].url.replace(baseUrl, "") + separator
    }
  }
  return strs != "" ? strs.substr(0, strs.length - 1) : ""
}

// 格式化文件大小
function formatFileSize(bytes) {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

// 开始上传 - 外部调用此方法
async function startUpload() {
  console.log('开始上传，rawFiles:', rawFiles.value)
  console.log('fileList:', fileList.value)
  
  if (rawFiles.value.length === 0) {
    proxy.$modal.msgWarning('请先选择要上传的文件')
    return {
      success: false,
      error: '没有选择文件'
    }
  }

  uploading.value = true
  uploadResult.value = null
  
  try {
    // 创建 FormData
    const formData = new FormData()
    
    // 添加文件，参数名为 files
    rawFiles.value.forEach(file => {
      formData.append('files', file)
    })
    
    // 添加其他参数
    if (props.data) {
      Object.keys(props.data).forEach(key => {
        formData.append(key, props.data[key])
      })
    }
    
    console.log('发送上传请求到:', uploadDicomUrl.value)
    
    // 发送上传请求
    const response = await fetch(uploadDicomUrl.value, {
      method: 'POST',
      headers: {
        'Authorization': 'Bearer ' + getToken()
      },
      body: formData
    })
    
    const result = await response.json()
    console.log('上传响应:', result)
    
    if (result.code === 200) {
      // 存储上传结果信息
      if (result.data) {
        uploadResult.value = {
          taskId: result.data.taskId,
          studyCount: result.data.studyCount,
          seriseCount: result.data.seriseCount,
          processedFiles: result.data.processedFiles
        }
      }
      
      // 更新文件状态
      fileList.value.forEach(file => {
        file.status = 'success'
      })
      
      proxy.$modal.msgSuccess(
        `上传完成！任务ID: ${uploadResult.value.taskId}, ` +
        `处理了 ${uploadResult.value.processedFiles} 个文件, ` +
        `生成了 ${uploadResult.value.studyCount} 个检查, ` +
        `${uploadResult.value.seriseCount} 个序列`
      )
      
      return {
        success: true,
        data: result.data
      }
    } else {
      throw new Error(result.msg || '上传失败')
    }
  } catch (error) {
    console.error('上传失败:', error)
    
    // 更新文件状态
    fileList.value.forEach(file => {
      file.status = 'error'
    })
    
    proxy.$modal.msgError(`上传失败: ${error.message}`)
    
    return {
      success: false,
      error: error.message
    }
  } finally {
    uploading.value = false
  }
}

// 清空所有文件
function clearFiles() {
  fileList.value = []
  rawFiles.value = []
  uploadResult.value = null
  emit("update:modelValue", "")
}

// 获取当前文件列表
function getFileList() {
  return fileList.value
}

// 获取文件数量
function getFileCount() {
  return rawFiles.value.length
}

// 获取总文件大小
function getTotalFileSize() {
  return totalFileSize.value
}

// 暴露方法给父组件
defineExpose({
  startUpload,
  clearFiles,
  getFileList,
  getFileCount,
  getTotalFileSize
})
</script>

<style scoped lang="scss">
.component-upload-dicom {
  .file-stats {
    margin: 15px 0;
  }
  
  .upload-result-card {
    margin-top: 20px;
    border: 1px solid #e1f5d9;
    background-color: #f8fff8;
    
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
  }
}

:deep(.hide .el-upload--text) {
    display: none;
}

:deep(.el-upload.el-upload--text.is-disabled) {
  display: none !important;
}

:deep(.el-upload-list__item) {
  transition: none;
}
</style>